package com.demo.controller.system;




import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.mapper.system.DeptMapper;
import com.demo.mapper.system.UserMapper;
import com.demo.pojo.DTO.DTOUserDept;
import com.demo.pojo.DTO.DTOUserPost;
import com.demo.pojo.DTO.DTOUserRole;
import com.demo.pojo.system.Dept;
import com.demo.pojo.VO.VODeptId;

import com.demo.pojo.PO.User;
import com.demo.dao.Result;
import com.demo.pojo.VO.VOUser;
import com.demo.service.system.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

// 用户管理
@RestController
@RequestMapping("/RMS/User")
@CrossOrigin // 跨域
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DeptMapper deptMapper;
    // 获取左侧树状图，点击后拿到树状图点击的treePath，显示归属的人员 // 默认进去给个1就能显示全部
    // userRoleId和userPostId 不想要就不传值或者传空字符串""
    @GetMapping
    public Result getAllUser(String treePath,int currentPage,int pageSize,
                             @RequestParam(required = false ,defaultValue = "") String need,
                             @RequestParam(required = false ,defaultValue = "") String userRoleId,
                             @RequestParam(required = false ,defaultValue = "") String userPostId){
        // roleId并不在user表内，需要额外过一遍userid
        List<DTOUserRole> user2;
        if (!userRoleId.equals("")){user2 = userMapper.selectRoleId(userRoleId);}
        else {user2 = null;};
        // 拿到tree数字，查询树下的机构id
        List<String> user1 = userMapper.selectDeptTree("%"+treePath+"%");
        // 查询归属于以上机构id的人
        LambdaQueryWrapper<User> wrapper = new QueryWrapper<User>().lambda()
                .eq(!userPostId.equals(""),User::getPostId,userPostId)
                .in(User::getDeptId, user1)
                .and(qw1->qw1.like(User::getName,need)
                        .or(qw->qw.like(User::getPhone,need))
                        .or(qw->qw.like(User::getUsername,need)));

        Page<User> page = new Page<>(currentPage,pageSize);
        List<User> userList = userMapper.selectPage(page,wrapper).getRecords();

        // 筛除不符合roleId条件的对象
        if(!userRoleId.equals("")){
            userList =  userList.stream().filter(m->{
                    return user2.stream()
                            .filter(m2->m2.getUserId().equals(m.getId()))
                            .collect(Collectors.toList())
                            .size()!=0;})
                .collect(Collectors.toList());
        };
        // 用getRecords()这个方法获取page类型内的内容转成list，才能使用list的方法处理数据
        List<VOUser> userList1 = makeUserToVO(userList);
            return Result.success(userList1);
    }


    // 将User表的信息转化为VOUser的信息
    public List<VOUser> makeUserToVO(List<User> userList){
            List<VOUser> userList1 = userList.stream().map(m->{
            VOUser user = new VOUser();
            user.setId(m.getId());
            user.setUsername(m.getUsername());
            user.setName(m.getName());
            user.setPhone(m.getPhone());
            user.setPostId(m.getPostId());
            user.setStatus(m.getStatus());
            user.setCreateTime(m.getCreateTime());
            // 调岗位表一一对应
            List<DTOUserPost> getPost = getPost();
            getPost.stream().filter(m2-> m2.getId().equals(m.getPostId())).forEach(m2->{
                user.setPost(m2.getName());
            });
            List<DTOUserRole> getRole = getRole();
            getRole.stream().filter(m2-> m2.getUserId().equals(m.getId())).forEach(m2->{
                user.setRole(m2.getRoleName());
                user.setRoleId(m2.getRoleId());
            });
            List<DTOUserDept> getDept = getDept();
            getDept.stream().filter(m2-> m2.getId().equals(m.getDeptId())).forEach(m2->{
                user.setDept(m2.getDeptName());
            });
            return user;
        }).collect(Collectors.toList());
        return userList1;
    }

    // 这几个是中间查询方法
    public List<DTOUserPost> getPost(){
        return userMapper.selectAllPost();
    }
    @GetMapping(value = "/getRole")
    public List<DTOUserRole> getRole(){
        return userMapper.selectAllUserRoleAndRole();
    }
    public List<DTOUserDept> getDept(){
        return userMapper.selectAllDept();
    }


    // 递归分层级 部门
    public List<VODeptId> getDeptStream(List<Dept> userList, List<VODeptId> userid){
        List<VODeptId> userid1=  userid.stream().map(m->{
            VODeptId VODeptId = new VODeptId();
            VODeptId.setName(m.getName());
            VODeptId.setDeptId(m.getDeptId());
            VODeptId.setTreePath(m.getTreePath());
            return VODeptId;
        }).map(m->{
            //拿到每个id再全部拿一次parentId进行对比
            List<VODeptId> VODeptId3 =  userList.stream().filter(m2->m2.getParentId().equals(m.getDeptId())).map(m2->{
                VODeptId VODeptId2 = new VODeptId();
                VODeptId2.setDeptId(m2.getId());
                VODeptId2.setName(m2.getName());
                VODeptId2.setTreePath(m2.getTreePath());
                return VODeptId2;
            }).collect(Collectors.toList());
            m.setSonId(VODeptId3);
//            System.out.println(m.getSonId().toArray().length);

            if (m.getSonId().toArray().length>0){
                 m.setSonId(getDeptStream(userList,m.getSonId()));
            }
            return m;
        }).collect(Collectors.toList());

        return userid1;
    }
    // 递归分层级
    @GetMapping(value = "/get")
    public Result getByDept(){
        //选择一次性拿出数据避免多次读取数据库费时间
        List<Dept> userList = deptMapper.selectList(null);
        // 转中转类型
        List<VODeptId> userId = userList.stream().map(m->{
            VODeptId VODeptId = new VODeptId();
            VODeptId.setDeptId(m.getId());
            VODeptId.setName(m.getName());
            VODeptId.setTreePath(m.getTreePath());
            return VODeptId;
        }).collect(Collectors.toList());

        List<VODeptId> getUserId = getDeptStream(userList,userId.subList(0,1));

        return Result.success(getUserId);
    }


    //新增用户
    @PostMapping(value = "/addUser")
    public Result addUser(@RequestBody User user){
        return Result.success(userMapper.insert(user));
    }
    //修改用户信息
    @PutMapping(value = "/putUser")
    public Result putUser(@RequestBody User user){
        return Result.success(userMapper.updateById(user));
    }


    // 设置用户状态码，把新的状态码修改好放对象里传过来，记得带上id
    @PutMapping(value = "/putUserStatus")
    public Result putUserStatus(@RequestBody User user){
        String UserStatus = "status = "+String.valueOf(user.getStatus());
        UpdateWrapper<User> queryWrapper = new UpdateWrapper<User>()
                .eq("id", user.getId())
                .setSql(UserStatus);
        return Result.success(userMapper.update( null,queryWrapper));
    }

    // 分配角色
    @GetMapping(value = "/getPutUserRole")
    public Result getPutUserDept(Integer userId){
        // 先用上面getRole拉取角色表做多选框选择
        // 用户id读取user_role联表role表格查到这个用户的角色信息/已经排除过isDeleted
        List<DTOUserRole> userRoleList = userMapper.selectUserRole(userId);
        return Result.success( userRoleList);
    }
    // 传入一个修改的数组，也就是这个用户修改完的所有他的角色数组
    @PutMapping(value = "/putUserRole")
    public Result putUserRole(@RequestBody List<DTOUserRole> userRole){
        // 查出这个用户的所有角色信息，包括软删除过的
        List<DTOUserRole> userRoleList = userMapper.selectAllUserRole(userRole.get(0).getUserId());
        // 遍历该用户的全部角色信息，和传入的用户角色信息比较角色id，存在则认为数据（id）在库内存在，把isdeleted设置为新状态
        Double i1 =  userRole.stream().mapToDouble(m->{
           double i = userRoleList.stream().filter(m2->{return m2.getRoleId().equals(m.getRoleId());})
                    .mapToDouble(m2 ->{
                        return userMapper.updateRole(m2.getId(), m2.getIsDeleted(), m2.getUserId());}).sum();
            return i;
        }).sum();
        // 重复如上操作，将认为不存在的数据新增
        i1 = i1+userRole.stream().mapToDouble(m->{
            // 寻找不存在的值
            double i = userRoleList.stream()
                    .filter(m2->{
                        return m2.getRoleId().equals(m.getRoleId());}).count();
            // 如果不存在，就新增，并计数，否则把计数设为0
            if(i == 0.0) {i = userMapper.addUserRole(m.getRoleId(),m.getUserId(),m.getIsDeleted());
            }else {i = 0.0;}
            return i;
        }).sum();
        return Result.success(i1);
    }

    // 删除用户
    @DeleteMapping(value = "/delUser")
    public Result delUser(@RequestBody User user){
        return Result.success( userMapper.deleteById(user.getId()));
    }
}
